package com.dy.栈;

import com.dy.栈.顺序栈.SqStack;

/*
左右括号，左括号入栈，遇到右括号，弹栈并比较
 */
public class 分隔符匹配 {
    public final int LEFT = 0;
    public final int RIGHT = 1;
    public final int OTHER = 2;

    //判断是左分隔符与否
    public int verifyFlag(String str) {
        if ("(".equals(str) || "[".equals(str) || "{".equals(str) || "/*".equals(str)) {
            return LEFT;
        } else if (")".equals(str) || "]".equals(str) || "}".equals(str) || "*/".equals(str)) {
            return RIGHT;
        } else return OTHER;
    }

    //判断两个括号是否匹配
    public boolean matches(String s1, String s2) {
        if (("(".equals(s1) && ")".equals(s2))
                || ("[".equals(s1) && "]".equals(s2))
                || ("{".equals(s1) && "}".equals(s2))
                || ("/*".equals(s1) && "*/".equals(s2))
        ) {
            return true;
        } else return false;
    }

    public boolean isLegal(String str) throws Exception {
        int len = str.length();
        if (len != 0) {
            SqStack stack = new SqStack(100);
            for (int i = 0; i < len; i++) {
                char c = str.charAt(i);
                String t = String.valueOf(c);
                if (i < len - 1) {
                    if (('/' == c && '*' == str.charAt(i + 1)) ||
                            ('*' == c && '/' == str.charAt(i + 1))
                    ) {
                        t = t.concat(String.valueOf(str.charAt(i + 1)));
                        i++;
                    }
                }
                if (verifyFlag(t) == LEFT) {
                    stack.push(t);
                } else if (verifyFlag(t) == RIGHT) {
                    if (stack.isEmpty() || !matches(stack.pop().toString(), t)) {
                        return false;
                    }
                }
            }
            return true;
        } else return false;
    }

    public static void main(String[] args) throws Exception {
        分隔符匹配 solution = new 分隔符匹配();
        String s="a=b+(c*d)/*[e-f]*/";
        System.out.println(solution.isLegal(s));
    }


}
